'''
Created on Jan 18, 2011

@author: Administrator
'''

import logging
logger = logging.getLogger(__name__)
import shell

from sniffylib.core import services


class SniffyCmd(object):
    
    def __init__(self, username, name, params):
        self.user = shell.User(username)
        self.name = name
        self.params = params

MSG_OK_TEMPL = '%s: ok'
MSG_ERROR_TEMPL = '%s: %s' 
MSG_BAD_CMD_ERROR = 'nieprawidlowa komenda'
MSG_UNDEFINED_ERROR = 'nieznany blad'

class ConsoleShellHandler:
    def handle_error(self, shell, msg):
        logger.debug('error: ', shell.master, msg)
        
    def handle_result(self, shell, msg):
        logger.debug('result: ', shell.master, msg)


class CmdException(Exception):    
    
    def __init__(self, msg='', got_auth=False):
        super(CmdException, self).__init__(msg)
        self.got_auth = got_auth

class BadCmdException(CmdException):

    def __init__(self, got_auth=False):
        super(BadCmdException, self).__init__(MSG_BAD_CMD_ERROR, got_auth)

class BadAuthCmdException(CmdException):
    pass

class CmdInternalException(CmdException):
    
    def __init__(self, got_auth=False, internal=None):
        super(CmdInternalException, self).__init__(MSG_UNDEFINED_ERROR, got_auth)
        self.internal = internal

def parse_cmdln(cmdln):
    cmd_els = cmdln.split(' ')
    name = cmd_els[0]
    args = cmd_els[1:]
    return name, args

class BaseRPCService(services.BaseService):
    
    def __init__(self, shell):
        services.BaseService.__init__(self)        
        self.shell = shell
        self.error_handler = None
        self.result_handler = None
    
    def dispatch_cmd(self, cmd):
        try:
            res = self.shell.interpret(cmd)
            self.dispatch_result(cmd, res)
        except CmdException, cmde:
            self.dispatch_error(cmd, cmde)
                    
    def dispatch_error(self, cmd, cmde):
        msg = MSG_ERROR_TEMPL % (cmd.name, cmde)
        logger.debug(msg)
        if self.error_handler and cmde.got_auth:
            self.error_handler.handle_error(self.shell, msg)            
        
    def dispatch_result(self, cmd, res):
        msg = MSG_OK_TEMPL % cmd.name
        logger.debug(msg)
        if self.result_handler:
            self.result_handler.handle_result(self.shell, msg)
        